package com.zyf.lj.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyf.lj.util.JwtUtil;
import com.zyf.lj.vo.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

/**
 * 认证拦截器
 */
@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    /**
     * 在请求处理之前进行调用
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求URI
        String uri = request.getRequestURI();
        log.info("请求URI: {}", uri);
        
        // 如果是微信登录等不需要验证的接口，直接放行
        if (isExcludedUri(uri)) {
            return true;
        }
        
        // 获取请求头中的token
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)) {
            // 如果没有token，返回未授权错误
            responseUnauthorized(response, "未登录，请先登录");
            return false;
        }
        
        // 如果token以Bearer开头，去掉前缀
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        // 验证token
        if (!jwtUtil.validateToken(token)) {
            responseUnauthorized(response, "登录已过期，请重新登录");
            return false;
        }
        
        // 将用户信息存入请求属性中，方便后续使用
        request.setAttribute("userId", jwtUtil.getUserIdFromToken(token));
        request.setAttribute("openid", jwtUtil.getOpenidFromToken(token));
        
        // 验证通过，放行
        return true;
    }
    
    /**
     * 判断是否为不需要验证的URI
     * @param uri 请求URI
     * @return 是否为不需要验证的URI
     */
    private boolean isExcludedUri(String uri) {
        // 微信登录等不需要验证的接口
        return uri.contains("/api/user/wx-login") || 
               uri.contains("/api/public/") ||
               uri.contains("/api/file/download") ||
               uri.contains("/swagger") ||
               uri.contains("/v3/api-docs") ||
               uri.contains("/doc.html") ||
               uri.contains("/api/enrollment/colleges") ||
               uri.contains("/api/enrollment/college") ||
               uri.contains("/api/enrollment/majors") ||
               uri.contains("/api/enrollment/major");
    }
    
    /**
     * 返回未授权错误
     * @param response 响应
     * @param message 错误信息
     */
    private void responseUnauthorized(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write(objectMapper.writeValueAsString(Result.fail(401, message)));
    }
} 